import editForm from "../form.vue";
import { message } from "@/utils/message";
import { ElMessageBox } from "element-plus";
import { usePublicHooks } from "../../hooks";
import { transformI18n } from "@/plugins/i18n";
import { addDialog } from "@/components/ReDialog";
import type { FormItemProps } from "../utils/types";
import type { PaginationProps } from "@pureadmin/table";
import { getKeyList, deviceDetection } from "@pureadmin/utils";
import {getDeptList, getPurchaseUserList, getRoleMenu, getRoleMenuIds} from "@/api/system";
import { type Ref, reactive, ref, onMounted, h, toRaw, watch } from "vue";
import { utils, writeFile, readFile } from "xlsx";


export function usePurchaseUser(treeRef: Ref) {
  const form = reactive({
    name: "",
    code: "",
    status: ""
  });
  const curRow = ref();
  const formRef = ref();
  const dataList = ref([]);
  const userList = ref([]);
  const isShow = ref(false);
  const loading = ref(true);
  const isLinkage = ref(false);
  const switchLoadMap = ref({});
  const isExpandAll = ref(false);
  const isSelectAll = ref(false);
  const { switchStyle } = usePublicHooks();
  const treeProps = {
    value: "id",
    label: "title",
    children: "children"
  };
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,pageSizes: [20, 40, 60,100,300,500],
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {label: "用户Id", prop: "user_id"},
    {label: "采购姓名", prop: "user.nickname"},
    {label: "采购用户名", prop: "user.username"},
    {label: "手机号", prop: "user.phone",},
    {label: "单笔提成", prop: "commission"},
    {label: "编号前缀", prop: "prefix_no"},
    {label: "每日接单上限", prop: "limit_upper"},
    {label: "今日接单数", prop: "today_number"},
    {
      label: "状态",
      cellRenderer: scope => (
        <el-switch
          size={scope.props.status === "small" ? "small" : "default"}
          loading={switchLoadMap.value[scope.index]?.loading}
          v-model={scope.row.status}
          active-value={1}
          inactive-value={2}
          active-text="已启用"
          inactive-text="已停用"
          inline-prompt
          style={switchStyle.value}
          onChange={() => onChange(scope as any)}
        />
      ),
      minWidth: 90
    },
    {label: "创建时间", prop: "created_at",width:160},
    {label: "添加人员", prop: "creator",width:160},
    {label: "操作", fixed: "right", width: 160, slot: "operation"}
  ];


  function onChange({ row, index }) {
    ElMessageBox.confirm(`确认要<strong>${row.status === 2 ? "停用" : "启用"}</strong>
        <strong style='color:var(--el-color-primary)'>${ row.name}</strong>吗?`, "系统提示",
      { confirmButtonText: "确定", cancelButtonText: "取消", type: "warning", dangerouslyUseHTMLString: true, draggable: true}).then(() => {
        row.swith = 1
        getPurchaseUserList(row,"put").then(res=>{
          switchLoadMap.value[index] = Object.assign(
            {},
            switchLoadMap.value[index],
            {
              loading: false
            }
          );
          message(`已${row.status === 2 ? "停用" : "启用"}${row.name}-${row.state}国家物流渠道`, {
            type: "success"
          });
        })
      }).catch(() => {
        row.status === 2 ? (row.status = 1) : (row.status = 2);
      });
  }

  function handleDelete(row) {
    getPurchaseUserList(row,"delete").then(res=>chores(row,res,'删除'))
  }

  function handleSizeChange(val: number) {
    pagination.pageSize = val
    onSearch()
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val
    onSearch()
  }


  async function onSearch() {
    loading.value = true;
    form.page = pagination.currentPage
    form.limit = pagination.pageSize
    const { data } = await getPurchaseUserList(toRaw(form),'get');
    dataList.value = data.data;
    userList.value = data.user_list;
    pagination.total = data.total;
    pagination.pageSize = data.per_page;
    pagination.currentPage = data.current_page;
    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };
  function chores(curData,res,title,done) {
    if(res.code===0){
      message(`您${title}了用户ID为${curData.user_id}的采购人员额度数据`, {type: "success"});
      if(done != undefined)done(); // 关闭弹框
      onSearch(); // 刷新表格数据
    }else{
      message(`${title}失败，原因：${res.message}`, {
        type: "error"
      });
    }
  }
  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}采购人员额度`,
      props: {
        formInline: JSON.parse(JSON.stringify(row||{status:1})),
        userList:userList.value
      },
      width: "45%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef, formInline: null }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        FormRef.validate(valid => {
          if (valid) {
            if (title === "新增") {
              // 实际开发先调用新增接口，再进行下面操作
              getPurchaseUserList(curData,"post").then(res=>chores(curData,res,title,done))
            } else {
              curData.id = row.id
              // 实际开发先调用修改接口，再进行下面操作
              getPurchaseUserList(curData,"put").then(res=>chores(curData,res,title,done))
            }
          }
        });
      }
    });
  }

  const exportExcel = async () => {
    const { data } = await getPurchaseUserList(toRaw({page:1,export:1}),'get');
    const res = data.field
    const workSheet = utils.aoa_to_sheet(res);
    const workBook = utils.book_new();
    utils.book_append_sheet(workBook, workSheet, "数据报表");
    writeFile(workBook, `采购人员额度${new Date().toISOString()}.xlsx`);
  };


  /** 高亮当前权限选中行 */
  function rowStyle({ row: { id } }) {
    return {
      cursor: "pointer",
      background: id === curRow.value?.id ? "var(--el-fill-color-light)" : ""
    };
  }

  const onQueryChanged = (query: string) => {
      treeRef.value!.filter(query);
    };

  const filterMethod = (query: string, node) => {
    return transformI18n(node.title)!.includes(query);
  };

  onMounted(async () => {
    onSearch();
  });


  return {
    form,
    isShow,
    curRow,
    loading,
    columns,
    rowStyle,
    dataList,
    isLinkage,
    pagination,
    isExpandAll,
    isSelectAll,
    userList,
    onSearch,
    resetForm,
    openDialog,
    exportExcel,
    handleDelete,
    filterMethod,
    transformI18n,
    onQueryChanged,
    // handleDatabase,
    handleSizeChange,
    handleCurrentChange
  };
}
